package com.back_end.NetWork.chart;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//接收方
public class TalkReceive implements Runnable{

    DatagramSocket socket  =   null;
    private int port;
    private String msgFrom;

    public TalkReceive(int port,String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        try {
            socket = new DatagramSocket(port);   //这是我接收端的端口
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while (true) {
            try {
                //准备接收包裹
                byte[] container = new byte[1024];
                //接收的容器，没容器，数据没地放
                DatagramPacket packet = new DatagramPacket(container,0,container.length);
                socket.receive(packet); //阻塞式接收到包裹

                byte[] data = packet.getData();   //取到字节数据
                String receiveData = new String(data,0, packet.getLength());  //转为字符串，此时取packet的length，因为取data.length的那便是1024个长度
                System.out.println(msgFrom+ ": " + receiveData); //输出数据
                //判断遇到bye，断开连接
                if(receiveData.equals("bye")){
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
